import requests
import json
import time
import random

# 英雄信息接口，返回Json格式的字符串
hero_url = "https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?ts=2883755"
headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
}
hero_pic_base_url = "https://game.gtimg.cn/images/lol/act/img/skinloading/{}.jpg"
hero_response = requests.get(url=hero_url, headers=headers)
# 通过json模块的loads方法解析 符合Json格式的字符串，最终将其转成类似Python中的Dict
hero_json_obj = json.loads(hero_response.text)
cnt = 0
# 将数据写入文件保存
with open("data/hero_info.csv", mode="w", encoding='utf8') as f:
    for hero in hero_json_obj["hero"]:
        # 提取每个英雄的信息
        heroId = hero['heroId']
        name = hero['name']
        alias = hero['alias']
        title = hero['title']
        roles = "|".join(hero['roles'])
        difficulty = hero['difficulty']
        goldPrice = hero['goldPrice']
        couponPrice = hero['couponPrice']
        camp = hero['camp']
        cnt += 1
        f.write(",".join(
            list((str(cnt), str(heroId), name, alias, title, roles, difficulty, goldPrice, couponPrice, camp))))
        f.write("\n")

        # 提取英雄的instance_id用于获取图片
        instance_id = hero['instance_id']
        hero_pic_url = hero_pic_base_url.format(instance_id)
        # 再次发起请求 获取英雄图片
        pic_res = requests.get(url=hero_pic_url, headers=headers)
        print("正在获取%s的封面" % name)
        # 获取返回的二进制内容，并通过二进制写入的方式保存到文件中
        with open("data/hero/%s-%s.jpg" % (cnt, name), mode="wb") as pic_f:
            pic_f.write(pic_res.content)
        # 手动的随机休眠一段时间，避免爬取太快招到网站的封禁
        # time.sleep(random.randint(1, 3))
